package service

import (
	"awesomeProject2/global"
	"awesomeProject2/model"
	"awesomeProject2/model/request"
	"awesomeProject2/model/response"
	"strconv"
)

func GetPatentsDynamic(info request.PatentSearchInfo) (err error, list interface{}, total int64) {
	var res []response.PatentResponse
	var userIds []uint
	limit := info.PageSize
	offset := info.PageSize * (info.PageNum - 1)
	db := global.GVA_DB.Model(&model.Patent{}).Select("teacher.teacher_name as name, patent.*").
		Joins("left join teacher on patent.user_id = teacher.user_id")

	if info.PatentName != "" {
		db = db.Where("patent_name LIKE ?", "%"+info.PatentName+"%")
	}

	if info.PatentNumber != "" {
		db = db.Where("patent_number = ?", info.PatentNumber)
	}

	if info.PatentCategory != "" {
		db = db.Where("patent_category = ?", info.PatentCategory)
	}

	if info.Year != "" {
		year, _ := strconv.Atoi(info.Year)
		db = db.Where("year = ?", year)
	}

	if info.Name != "" {
		userIds, err = model.GetUserIdsByTeacherName(info.Name)
		if len(userIds) != 0 {
			db = db.Where("teacher.user_id IN ?", userIds)
		}
	}

	err = db.Count(&total).Error
	if err != nil {
		return err, nil, 0
	}

	err = db.Limit(limit).Offset(offset).Find(&res).Error
	return err, res, total

}
